package com.mes.biz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mes.biz.domain.*;
import com.mes.biz.mapper.BizAfterSaleOrderMapper;
import com.mes.biz.mapper.BizCustomerPayableDetailMapper;
import com.mes.biz.mapper.BizCustomerPayableMapper;
import com.mes.biz.service.*;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.page.PageDomain;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import com.mes.system.domain.SysTenant;
import com.mes.system.service.SysTenantService;
import com.mes.system.strategy.AutoCodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 售后单Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-03-27
 */
@Service
public class BizAfterSaleOrderServiceImpl extends BaseServiceImpl<BizAfterSaleOrderMapper, BizAfterSaleOrder> implements BizAfterSaleOrderService {

    @Resource
    private BizAfterSaleOrderMapper bizAfterSaleOrderMapper;
    @Resource
    private BizAfterSaleOrderAttachService bizAfterSaleOrderAttachService;
    @Resource
    private SysTenantService sysTenantService;
    @Resource
    private BizCustomerPayableService bizCustomerPayableService;
    @Resource
    private BizCustomerPayableDetailService bizCustomerPayableDetailService;
    @Resource
    private BizCustomerPayableMapper bizCustomerPayableMapper;
    @Resource
    private BizCustomerPayableDetailMapper bizCustomerPayableDetailMapper;
    @Resource
    private BizOrderService bizOrderService;
    @Resource
    private AutoCodeUtil autoCodeUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createAfterSaleOrder(BizAfterSaleOrder bizAfterSaleOrder) {
        String tenantId = SecurityUtils.getTenantId();
        bizAfterSaleOrder.setTenantId(tenantId);
        if(StringUtils.isEmpty(bizAfterSaleOrder.getSaleOrderCode())) {
            SysTenant sysTenant = sysTenantService.get(tenantId);
            if (StringUtils.isEmpty(sysTenant.getLeader())){
                throw new BizException("请联系管理员添加售后单单前缀!");
            }
            String code = autoCodeUtil.genSerialCode("AFTER_SALE_ORDER_CODE",sysTenant.getLeader());
            bizAfterSaleOrder.setSaleOrderCode(code);
        } else {
            if(bizAfterSaleOrderMapper.getByOrderNumber(bizAfterSaleOrder.getOrderNumber())!=null) {
                throw new BizException("售后单编号已存在!");
            }
        }
        bizAfterSaleOrder.setStatus(BaseEntity.WAIT_HAHDLE);
        save(bizAfterSaleOrder);
        List<BizAfterSaleOrderAttach> saleOrderAttaches = bizAfterSaleOrder.getSaleOrderAttaches();
        if (saleOrderAttaches != null && saleOrderAttaches.size()>0){
            saveAfterSaleAttach(saleOrderAttaches,bizAfterSaleOrder);
        }
        System.err.println(bizAfterSaleOrder.getFeedAmount().compareTo(BigDecimal.ZERO)>0);
        if(bizAfterSaleOrder.getFeedAmount()!=null && bizAfterSaleOrder.getFeedAmount().compareTo(BigDecimal.ZERO)>0) {
            //写入应收账款
            //判断是否存在应收账款记录
           BizOrder bizOrder =  bizOrderService.get(bizAfterSaleOrder.getOrderId());
            BizCustomerPayable bizCustomerPayable = bizCustomerPayableService.getBizCustomerPayableByCustomerId(bizOrder.getCustomerId());
            if(bizCustomerPayable==null) {
                bizCustomerPayable = new BizCustomerPayable();
                bizCustomerPayable.setCustomerId(bizOrder.getCustomerId());
                bizCustomerPayable.setCustomerName(bizOrder.getCustomerName());
                bizCustomerPayable.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
                bizCustomerPayable.setPayAmount(BigDecimal.ZERO);
                bizCustomerPayable.setHasAmount(bizAfterSaleOrder.getFeedAmount());
                bizCustomerPayable.setTenantId(SecurityUtils.getTenantId());
                bizCustomerPayableService.save(bizCustomerPayable);
            } else {
                bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().add(bizAfterSaleOrder.getFeedAmount()));
                bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().add(bizAfterSaleOrder.getFeedAmount()));
                bizCustomerPayableMapper.update(bizCustomerPayable);
            }
            //写入明细
            BizCustomerPayableDetail bizCustomerPayableDetail = new BizCustomerPayableDetail();
            bizCustomerPayableDetail.setCustomerId(bizOrder.getCustomerId());
            bizCustomerPayableDetail.setCustomerName(bizOrder.getCustomerName());
            bizCustomerPayableDetail.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
            bizCustomerPayableDetail.setPayAmount(BigDecimal.ZERO);
            bizCustomerPayableDetail.setOrderNumber(bizAfterSaleOrder.getSaleOrderCode());
            bizCustomerPayableDetail.setTenantId(SecurityUtils.getTenantId());
            bizCustomerPayableDetail.setAfterSaleOrderId(bizAfterSaleOrder.getId());
            bizCustomerPayableDetail.setType("2");//售后单
            bizCustomerPayableDetailService.save(bizCustomerPayableDetail);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAfterSaleOrder(BizAfterSaleOrder bizAfterSaleOrder) {
        if(null != bizAfterSaleOrder.getProcessUserId()) {
            bizAfterSaleOrder.setStatus(BaseEntity.IS_HAHDLE);
        }
        int update = bizAfterSaleOrderMapper.update(bizAfterSaleOrder);

        //修改售后图片
        //删除
        bizAfterSaleOrderAttachService.removeBySaleOrderId(bizAfterSaleOrder.getId(),"1");
        //新增
        List<BizAfterSaleOrderAttach> saleOrderAttaches = bizAfterSaleOrder.getSaleOrderAttaches();
        if (saleOrderAttaches != null && saleOrderAttaches.size()>0){
            saveAfterSaleAttach(saleOrderAttaches,bizAfterSaleOrder);
        }

        if(bizAfterSaleOrder.getFeedAmount()!=null && bizAfterSaleOrder.getFeedAmount().compareTo(BigDecimal.ZERO)>0) {
            //写入应收账款
            //判断是否存在应收账款记录
            BizOrder bizOrder =  bizOrderService.get(bizAfterSaleOrder.getOrderId());
            BizCustomerPayable bizCustomerPayable = bizCustomerPayableService.getBizCustomerPayableByCustomerId(bizOrder.getCustomerId());
            if(bizCustomerPayable==null) {
                bizCustomerPayable = new BizCustomerPayable();
                bizCustomerPayable.setCustomerId(bizOrder.getCustomerId());
                bizCustomerPayable.setCustomerName(bizOrder.getCustomerName());
                bizCustomerPayable.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
                bizCustomerPayable.setPayAmount(BigDecimal.ZERO);
                bizCustomerPayable.setHasAmount(bizAfterSaleOrder.getFeedAmount());
                bizCustomerPayable.setTenantId(SecurityUtils.getTenantId());
                bizCustomerPayableService.save(bizCustomerPayable);
                //写入明细
                BizCustomerPayableDetail bizCustomerPayableDetail = new BizCustomerPayableDetail();
                bizCustomerPayableDetail.setCustomerId(bizOrder.getCustomerId());
                bizCustomerPayableDetail.setCustomerName(bizOrder.getCustomerName());
                bizCustomerPayableDetail.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
                bizCustomerPayableDetail.setPayAmount(BigDecimal.ZERO);
                bizCustomerPayableDetail.setOrderNumber(bizAfterSaleOrder.getSaleOrderCode());
                bizCustomerPayableDetail.setTenantId(SecurityUtils.getTenantId());
                bizCustomerPayableDetail.setAfterSaleOrderId(bizAfterSaleOrder.getId());
                bizCustomerPayableDetail.setType("2");//售后单
                bizCustomerPayableDetailService.save(bizCustomerPayableDetail);
            } else {
                BizCustomerPayableDetail bizCustomerPayableDetail = bizCustomerPayableDetailService.getByAfterSaleOrderId(bizAfterSaleOrder.getId());
                if(bizCustomerPayableDetail==null) {
                    bizCustomerPayableDetail = new BizCustomerPayableDetail();
                    bizCustomerPayableDetail.setCustomerId(bizOrder.getCustomerId());
                    bizCustomerPayableDetail.setCustomerName(bizOrder.getCustomerName());
                    bizCustomerPayableDetail.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
                    bizCustomerPayableDetail.setPayAmount(BigDecimal.ZERO);
                    bizCustomerPayableDetail.setOrderNumber(bizAfterSaleOrder.getSaleOrderCode());
                    bizCustomerPayableDetail.setTenantId(SecurityUtils.getTenantId());
                    bizCustomerPayableDetail.setAfterSaleOrderId(bizAfterSaleOrder.getId());
                    bizCustomerPayableDetail.setType("2");//售后单
                    bizCustomerPayableDetailService.save(bizCustomerPayableDetail);
                } else {
                    BigDecimal oldAmount = bizCustomerPayableDetail.getTotalAmount();
                    bizCustomerPayableDetail.setTotalAmount(bizAfterSaleOrder.getFeedAmount());
                    bizCustomerPayableDetailMapper.update(bizCustomerPayableDetail);

                    //修改应收
                    bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().add(oldAmount.subtract(bizCustomerPayableDetail.getTotalAmount())));
                    bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().add(oldAmount.subtract(bizCustomerPayableDetail.getTotalAmount())));
                }
            }
        } else {
            //删除应收
            BizOrder bizOrder =  bizOrderService.get(bizAfterSaleOrder.getOrderId());
            BizCustomerPayable bizCustomerPayable = bizCustomerPayableService.getBizCustomerPayableByCustomerId(bizOrder.getCustomerId());
            if(bizCustomerPayable!=null) {
                BizCustomerPayableDetail bizCustomerPayableDetail = bizCustomerPayableDetailService.getByAfterSaleOrderId(bizAfterSaleOrder.getId());
                if(bizCustomerPayableDetail!=null) {
                    bizCustomerPayableDetailService.remove(bizCustomerPayableDetail);
                    bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().subtract(bizCustomerPayableDetail.getTotalAmount()));
                    bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().subtract(bizCustomerPayableDetail.getTotalAmount()));
                    bizCustomerPayableMapper.update(bizCustomerPayable);
                }
            }
        }

        if(update > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAppletAfterSaleOrder(BizAfterSaleOrder bizAfterSaleOrder) {

        int update = bizAfterSaleOrderMapper.update(bizAfterSaleOrder);
        //修改售后图片
        //删除
        bizAfterSaleOrderAttachService.removeBySaleOrderId(bizAfterSaleOrder.getId(),"2");
        //新增
        List<BizAfterSaleOrderAttach> saleOrderAttaches = bizAfterSaleOrder.getAfterSaleOrderAttaches();
        if (saleOrderAttaches != null && saleOrderAttaches.size()>0){
            saveAfterSaleAttach(saleOrderAttaches,bizAfterSaleOrder);
        }
        if(update > 0) {
            return true;
        }
        return false;
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveAfterSaleAttach(List<BizAfterSaleOrderAttach> saleOrderAttaches, BizAfterSaleOrder bizAfterSaleOrder){
        for (BizAfterSaleOrderAttach bizAfterSaleOrderAttach:saleOrderAttaches){
            bizAfterSaleOrderAttach.setAfterSaleOrderId(bizAfterSaleOrder.getId());
            bizAfterSaleOrderAttach.setTenantId(bizAfterSaleOrder.getTenantId());
            bizAfterSaleOrderAttachService.save(bizAfterSaleOrderAttach);
        }
    }

    @Override
    public PageInfo<BizAfterSaleOrder> appletList(BizAfterSaleOrder bizAfterSaleOrder) {
        PageDomain page = bizAfterSaleOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }

        return new PageInfo(mapper.appletList(bizAfterSaleOrder));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(BizAfterSaleOrder bizAfterSaleOrder) {
        if(null != bizAfterSaleOrder.getProcessUserId()) {
            bizAfterSaleOrder.setStatus(BaseEntity.IS_HAHDLE);
        }
        int update = bizAfterSaleOrderMapper.update(bizAfterSaleOrder);
        if(update > 0) {
            return true;
        }
        return false;
    }
}
